package com.gewu.bluetoothflow.ui

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.database.Cursor
import android.net.Uri
import android.net.wifi.ScanResult
import android.net.wifi.WifiManager
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import com.eciot.ble_demo_kotlin.ECBLE
import com.gewu.bluetoothflow.MyApp.Companion.ACTION_SEND_DATA
import com.gewu.bluetoothflow.MyApp.Companion.FILE_SELECT_CODE
import com.gewu.bluetoothflow.R
import com.gewu.bluetoothflow.bean.BleDeviceInfo
import com.gewu.bluetoothflow.bean.UpgradeInfo
import com.gewu.bluetoothflow.databinding.ActivityWificonfigBinding
import com.gewu.bluetoothflow.service.DataRefreshReceiver
import com.gewu.bluetoothflow.view.LoadingDialog
import com.gewu.bluetoothflow.view.TipDialog
import com.google.gson.Gson
import java.io.File
import java.net.HttpURLConnection
import java.net.URL
import java.util.*


class WifiDevConfigActivity :BaseActivity(), DataRefreshReceiver.Messages {
    val TAG: String = "DevConfigActivity"
    private lateinit var mbinding: ActivityWificonfigBinding;
    private  var currentDevice:BleDeviceInfo? = null
    private  var wifiManager:WifiManager? = null


    var dataReceiver: DataRefreshReceiver? = null;
    var loadingDialog:LoadingDialog? = null
    var mTimer:Timer? = null
    var wifis:MutableList<String> = mutableListOf()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mbinding = ActivityWificonfigBinding.inflate(layoutInflater)
        setContentView(mbinding.root)

        val dev =  intent.getStringExtra("devInfo")
        currentDevice = Gson().fromJson(dev, BleDeviceInfo::class.java)


        mbinding.tvBack.setOnClickListener {
            finish()
        }
        wifiManager= application.getSystemService(Context.WIFI_SERVICE) as WifiManager

        mbinding.wifiSave.setOnClickListener {
           val name = mbinding.wName.text.toString().trim()
            if (name.isNullOrEmpty()){
                showToast(getString(R.string.wifi_name_null))
                return@setOnClickListener
            }
            val pass = mbinding.wifiPw.text.toString().trim()
            val encry = hashwf.get(name)
            val command2 =  "{\"wifiName\":\"$name\",\"wifiPass\":\"$pass\",\"wifiEnc\":\"$encry\"}"
            Log.d(TAG,"--> $command2")
            val state = ECBLE.writeBLECharacteristicValue(command2, false)
            if (state){
                showToast(resources.getString(R.string.save_success))
            }else{
                showToast(resources.getString(R.string.save_fail))
            }

        }

        dataReceiver = DataRefreshReceiver(this)
        val initentFilter = IntentFilter()
        initentFilter.addAction(ACTION_SEND_DATA)
        registerReceiver(dataReceiver,initentFilter,Context.RECEIVER_NOT_EXPORTED)
    }
    override fun onStart() {
        super.onStart()
        initView()
    }
    var hashwf = mutableMapOf<String,String>()

   @SuppressLint("MissingPermission")
   fun initView(){
       if (currentDevice!!.time.length != 14 ){
           return
       }

       mbinding.wName.setText(currentDevice!!.wifiName)
       mbinding.wifiPw.setText(currentDevice!!.wifiPass)
       mbinding.setIp.setText(currentDevice!!.addr)
       mbinding.setProt.setText("${currentDevice!!.port}")

       mbinding.searchWifi.setOnClickListener {
           if (!wifiManager!!.isWifiEnabled) {
               wifiManager!!.setWifiEnabled(true)
           }

           wifiManager!!.startScan()
           val scanResults:List<ScanResult> = wifiManager!!.scanResults
           wifis.clear()

           for (scanResult in scanResults) {
               if (scanResult.SSID.length > 1) {
                   val rssi = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                       wifiManager!!.calculateSignalLevel(scanResult.level)
                   } else {
                       WifiManager.calculateSignalLevel(scanResult.level, 10)
                   }
                   var encryptionType = checkSecurity(scanResult.capabilities)
                   //rssi  值越大信号越强
                   Log.d(TAG, "" + scanResult.SSID + "-->" + scanResult.level + "rssi:" + rssi  + " encry: "+encryptionType)
                   if (rssi > 5){ //收集信号强的wifi
                       hashwf.put(scanResult.SSID,encryptionType)
                   }
               }
           }
           wifis.addAll(hashwf.keys)
           val adapter = ArrayAdapter (this,R.layout.spinner_item,wifis)
           mbinding.wifiName.adapter = adapter

           mbinding.wifiName.setSelection(0)
           mbinding.wifiName.onItemSelectedListener = object :AdapterView.OnItemSelectedListener{
               override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
                   Log.d(TAG,"====> i : $p2  p3:$p3  name:${wifis.get(p2)}" )
                   val wifiName = wifis.get(p2)
                   mbinding.wName.setText(wifiName)
               }

               override fun onNothingSelected(p0: AdapterView<*>?) {

               }

           }


       }



       mbinding.testServer.setOnClickListener {
          val ip = mbinding.setIp.text.toString().trim()
           if (ip.isNullOrEmpty()){
               showToast(resources.getString(R.string.ip_name_null))
               return@setOnClickListener
           }
          val port = mbinding.setProt.text.toString().trim()
           if (port.isNullOrEmpty()){
               showToast(resources.getString(R.string.port_null))
               return@setOnClickListener
           }
           Thread{   //  /api/data
               val state = isServerReachable("http://$ip:$port/api/data")
               runOnUiThread {
                   mbinding.connectState.setText(if (state) "已连接" else "未连接")
               }
           }.start()
       }
       mbinding.serverSave.setOnClickListener {
           val ip = mbinding.setIp.text.toString().trim()
           val port = mbinding.setProt.text.toString().trim()
           if (ip.isNullOrEmpty()){
               showToast(resources.getString(R.string.ip_name_null))
               return@setOnClickListener
           }
           if (port.isNullOrEmpty()){
               showToast(resources.getString(R.string.port_null))
               return@setOnClickListener
           }
           val command2 =  "{\"addr\":\"$ip\",\"port\":\"$port\",\"api\":\"/api/data\"}"
           Log.d(TAG,"--> $command2")
           val state = ECBLE.writeBLECharacteristicValue(command2, false)
           if (state){
               showToast(resources.getString(R.string.save_success))
           }else{
               showToast(resources.getString(R.string.save_fail))
           }
       }

   }


    fun isServerReachable(url: String): Boolean {
        try {
            val url = URL(url)
            val connection = url.openConnection() as HttpURLConnection
            connection.requestMethod = "GET"
            connection.connectTimeout = 5000 // 设置连接超时时间
            connection.readTimeout = 5000 // 设置读取超时时间
            val responseCode = connection.responseCode
            return (responseCode == HttpURLConnection.HTTP_OK)
        } catch (e: Exception) {
            // 处理异常，例如网络不可用、服务器无响应等
            return false
        }
    }




    fun checkSecurity(capabilities: String) :String{
        var type = "Unknown"
        if (capabilities != null) {
            if (capabilities.contains("WEP")) {
                type = "WEP"
                //Log.d("Security", "WEP");
            } else if (capabilities.contains("WPA") || capabilities.contains("WPA2")) {
                if (capabilities.contains("PSK")) {
                    type = "WPA/WPA2 PSK"
                    //Log.d("Security", "WPA/WPA2 PSK");
                } else if (capabilities.contains("EAP")) {
                    type = "WPA/WPA2 Enterprise"
                    //Log.d("Security", "WPA/WPA2 Enterprise");
                } else {
                    type = "WPA/WPA2"
                    //Log.d("Security", "WPA/WPA2");
                }
            } else {
                type = "None/Open"
                //Log.d("Security", "None/Open");
            }
        }
        return type
    }

    override fun onStop() {
        super.onStop()
    }

    var mfilePath = ""  //固件路径
    override fun getMsg(str: String) {
        Log.d(TAG," --> "+str)
        if (str.contains("state")) {
            val bean = Gson().fromJson(str, UpgradeInfo::class.java)
            if (bean.state.equals("begin")) {
                if (mfilePath.length < 2) return
                val state = ECBLE.writeBLECharacteristicFile(File(mfilePath))
                mTimer!!.schedule(
                    object : TimerTask() {
                        override fun run() {
                            runOnUiThread {
                                if (loadingDialog != null) {
                                    loadingDialog!!.dismiss()
                                    showToast(resources.getString(R.string.fail_upgrade))
                                }
                            }
                        }
                    }, 300000
                )
            } else if (bean.state.equals("ok")) { //升级完成
                if (mTimer != null) {
                    mTimer!!.cancel()
                }
                if (loadingDialog != null) {
                    loadingDialog!!.dismiss()
                    showToast(resources.getString(R.string.success_upgrade))
                }
            }else if (bean.state.equals("error")){
                if (mTimer != null) {
                    mTimer!!.cancel()
                }
                if (loadingDialog != null) {
                    loadingDialog!!.dismiss()
                    showToast(resources.getString(R.string.fail_upgrade))
                }
            }
        }

        //{"info":"upgrade","state":"begin" } UpgradeInfo
        //{"info":"upgrade",”state“:"ok" }
        //{"info":"upgrade","len":541256 }    发送
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == FILE_SELECT_CODE && resultCode == RESULT_OK && data != null){
            val uri = data.data
            mfilePath = getFilePathFromUri(uri)
            //Log.d(TAG,"选择的文件路径 --> "+mfilePath)
            if (mfilePath.length < 2)return
            val mdialog = TipDialog(this, R.style.TransparentDialog,getString(R.string.ver_upgrade),mfilePath)
            mdialog.show()
            mdialog.setSaveListener(object :TipDialog.EditDevClickListener {
                override fun onclickSave() {
                    val file = File(mfilePath)
                    val len = file.length()
                    val command =  " {\"info\":\"upgrade\",\"len\":$len }"
                    Log.d(TAG,"文件大小 --> "+command)
                    mdialog.dismiss()
                    loadingDialog = LoadingDialog(this@WifiDevConfigActivity, R.style.TransparentDialog)
                    loadingDialog!!.show()
                    Thread{
                        val state = ECBLE.writeBLECharacteristicValue(command, false)
                    }.start()
                }
            })
        }
    }

    fun getFilePathFromUri( uri: Uri?):String{
        var path = ""
        if ("content".equals(uri!!.scheme,true)){
            val projection = MediaStore.MediaColumns.DATA
            var cursor: Cursor? = null
            try {
                cursor = contentResolver.query(uri, arrayOf(projection),null,null,null)
                if (cursor != null && cursor.moveToFirst()) {
                    val columnIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
                    path = cursor.getString(columnIndex);
                }
            } finally {
                if (cursor != null) {
                    cursor.close();
                }
            }
        } else if ("file".equals(uri.getScheme(),true)) {
            path = uri.getPath().toString();
        }
       return path
    }
































    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(dataReceiver)
    }




}